package com.aca.market.common;

import com.aca.market.entity.Storage;
import com.aca.market.mapper.StorageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
//3分钟查一次表 看看有没有更新 有就给后台侧栏贴标签
public class ScheduleTask {

    @Autowired
    StorageMapper storageMapper;

//    //改成service层里去写有返回的异步方法  这里只调用 返回布尔
//    @Async("asyncServiceExecutor")
//    @Scheduled(cron = "30/59 1/3 * * * ?")  //1分钟开始 每3分钟一次(从上一次的开始到下一次的开始)
//    public Future<Boolean> first() throws InterruptedException {
//
//        log.info("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
//        Thread.sleep(1000 * 10);
//        log.info("第一个定时任务结束 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
//        return new AsyncResult<>(Boolean.FALSE);
//    }

    @Scheduled(cron = "0 0/3 * * * ?")
//    @Scheduled(cron = "0 0/1 * * * ?")
    @Async("asyncServiceExecutor")
    public void checkStorage() {
        log.info("CheckStorage : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
        List<Storage> storage = storageMapper.checkStorage();
        for (Storage sto : storage) {
            log.info("==================STORAGE WARN:"
                    + sto.getItemName()
                    + ", 剩余: " + sto.getInventory()
                    + ", 预警余量:" + sto.getInventoryWarn());
        }
        //解决 UnavailableSecurityManagerException
//        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) context.getBean("securityManager");
//        SecurityUtils.setSecurityManager(securityManager);
//        Session session = SecurityUtils.getSubject()==null?null:SecurityUtils.getSubject().getSession();
//        if (session != null){
//            session.setAttribute("notice",storage);
//        }
        log.info("CheckStorage : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
    }


//    @Async
//    @Scheduled(fixedDelay = 2000)//间隔2秒
//    public void second() {
//        System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
//        System.out.println();
//    }
}
